package com.kingsoft.dc.khaos.module.spark.model.TechCheck;

import java.util.regex.Pattern;

public class KsyunNumberCheckRule extends KsyunCheckRule {
    private static final Pattern intPattern = Pattern.compile("[1-9][0-9]*|0"); //123
    private static final Pattern floatPattern = Pattern.compile("([1-9]+[0-9]*|0)(\\.[\\d]+)?"); //123.23

    private String dataType;
    private int lenth; //字符串总长度
    private int decimalLength; // 小数点长度
    //是否定长 ： true 定长字符串，false 不定长字符串
    private boolean isfixedlength;
    public KsyunNumberCheckRule(String dataType, int lenth, int decimalLength, boolean isfixedlength){
        this.dataType = dataType;
        this.lenth = lenth;
        this.decimalLength = decimalLength;
        this.isfixedlength = isfixedlength;
    }

    @Override
    public Tuple4<String,String, KsyunErrorCode,String> check(String value) {
        String tmpVal = value.trim();
        if(value.endsWith(" ")) {  //左侧补空格,不能以空格结尾
            throw getException("数值型字段需左侧补空格！规则："+dataType+ "实际值：" + value);
        }else if(isfixedlength && value.length() != lenth+1 ){  //定长字段判断 +1 是符号位
            throw getException("定长字段，长度错误！规则："+dataType+ "实际值：" + value);
        }else if(tmpVal.length()>lenth+1){   //非定长字段 长度超长 +1 是符号位
            throw getException("规则："+dataType+ "实际值：" + value);
        }
        if(tmpVal.startsWith("-"))  // 去掉符号位
            tmpVal = tmpVal.substring(1);

        if(decimalLength == 0){
            //decimalLength =0 表示没有小数点，是整型
            if(!intPattern.matcher(tmpVal).matches()){
                throw new KsyunTechCheckException(KsyunErrorCode.INT_LEGAL_CHECK,"规则："+dataType+ "实际值：" + value);
            }
        }else{
            //decimalLength >0 表示有小数点，是浮点型
            if(!floatPattern.matcher(tmpVal).matches() || tmpVal.length() - tmpVal.indexOf(".")-1 != decimalLength ){
                throw new KsyunTechCheckException(KsyunErrorCode.FLOAT_LEGAL_CHECK,"规则："+dataType+ "实际值：" + value);
            }
        }
        return null;
    }
    public KsyunTechCheckException getException(String msg){
        if (decimalLength == 0)
            throw new KsyunTechCheckException(KsyunErrorCode.INT_LENG_CHECK, msg);
        else
            throw new KsyunTechCheckException(KsyunErrorCode.FLOAT_LENG_CHECK, msg);
    }

    public static void main(String[] args) {
        KsyunCheckRule rule = KsyunCheckRule.ddlDataTypeParse("10n",0);
        Tuple4 res = rule.check("12345678910");
    }
}
